﻿using Caliburn.Micro;
using GetMan.Core.Extensions;
using GetMan.Core.infrastructure.BaseC;
using GetMan.Core.Models;
using GetMan.Results;
using Rubyer;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using System.Windows.Controls;

namespace GetMan.ViewModels
{
    /// <summary>
    /// Url参数列表文本框
    /// </summary>
    [Export(typeof(ParamsListViewModel))]
    public class ParamsListViewModel : ViewModelBase<ParamsListViewModel>
    {
        public ParamsListViewModel(string url) : base()
        {
            Url = url;
            var paramsList = new List<ParamsModel>();
            paramsList.Add(new ParamsModel()
            {
                ShowCheckBox = false,
                ShowWaterMark = true
            });
            ParamsList = new BindableCollection<ParamsModel>(paramsList);
        }

        #region 属性
        /// <summary>
        /// 选项数据集合
        /// </summary>
        private BindableCollection<ParamsModel> _paramsList;
        public BindableCollection<ParamsModel> ParamsList
        {
            get => _paramsList;
            set
            {
                _paramsList = value;
                NotifyOfPropertyChange(() => ParamsList);
            }
        }

        /// <summary>
        /// 请求URL
        /// </summary>
        private string _url;
        public string Url
        {
            get => _url;
            set
            {
                if (_url == value)
                    return;
                _url = value;
                NotifyOfPropertyChange(() => Url);
            }
        }

        /// <summary>
        /// Url参数列表
        /// </summary>
        private bool _paramsListAllChecked;
        public bool ParamsListAllChecked
        {
            get => _paramsListAllChecked;
            set
            {
                _paramsListAllChecked = value;
                NotifyOfPropertyChange(() => ParamsListAllChecked);
            }
        }

        /// <summary>
        /// 是否切换BulkEdit模式
        /// </summary>
        private bool isBulkEdit;
        public bool IsBulkEdit
        {
            get => isBulkEdit;
            set
            {
                isBulkEdit = value;
                NotifyOfPropertyChange(() => IsBulkEdit);
            }
        }

        private string _BulkEditTextBox;
        public string BulkEditTextBox
        {
            get => _BulkEditTextBox;
            set
            {
                _BulkEditTextBox = value;
                NotifyOfPropertyChange(() => BulkEditTextBox);
            }
        }
        #endregion

        #region ParamList
        /// <summary>
        /// 切换KeyValueEdit
        /// </summary>
        public void BulkEdit()
        {
            IsBulkEdit = true;
            //配置文本框焦点
            var focusResult = new FocusResult("BulkEditTextBox");
            Execute.OnUIThread(() =>
            {
                var context = new CoroutineExecutionContext { Target = this, View = GetView() };
                focusResult.Execute(context);
            });

            #region 解析选项对象
            StringBuilder sb = new StringBuilder();
            foreach (var p in ParamsList)
            {
                if (!p.ShowCheckBox)
                    continue;
                if (!p.IsChecked)
                {
                    sb.AppendLine($"//{p.Key}:{p.Value}");
                }
                else
                {
                    sb.AppendLine($"{p.Key}:{p.Value}");
                }
            }
            BulkEditTextBox = sb.ToString();
            #endregion
        }

        /// <summary>
        /// 切换BulkEdit
        /// </summary>
        public void KeyValueEdit()
        {
            IsBulkEdit = false;

        }

        public void ResetLst(string url, IEnumerable<ParamsModel> newLst)
        {
            Url = url;
            ParamsList.Clear();
            if (newLst != null && newLst.Any())
                ParamsList.AddRange(newLst);
            ParamsList.Add(new ParamsModel()
            {
                ShowWaterMark = true,
            });
            UpdateUrl();
        }

        /// <summary>
        /// 解析字符串
        /// </summary>
        public void OnBulkTextBoxChanged()
        {
            #region 解析字符串
            if (BulkEditTextBox.IsNull())
            {
                ParamsList.Clear();
                ParamsList.Add(new ParamsModel()
                {
                    ShowWaterMark = true,
                });
                return;
            }
            BulkEditTextBox = BulkEditTextBox.Replace("\t", "");
            string[] lines = BulkEditTextBox.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
            var currList = ParamsList.Where(x => x.ShowCheckBox).ToList();
            if (currList.Count() > lines.Count() && lines.Any())
            {
                int differ = currList.Count() - lines.Count();
                currList.RemoveRange(lines.Count() - 1, differ);
            }

            for (int i = 0; i < lines.Count(); i++)
            {
                string line = lines[i];
                line = line.Replace("\n", "");
                line = line.Replace("\r", "");
                line = line.Replace("\t", "");
                var cols = line.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
                if (currList.Count > i)
                {
                    currList[i].Key = cols.Length > 0 ? cols[0].Replace("//", "")?.Trim() : "";
                    currList[i].Value = cols.Length > 1 ? cols[1]?.Trim() : "";
                    if (line.StartsWith("//"))
                    {
                        currList[i].IsChecked = false;
                    }
                    else
                    {
                        currList[i].IsChecked = true;
                    }
                    currList[i].ShowBtnDel = true;
                }
                else
                {
                    currList.Add(new ParamsModel
                    {
                        Key = cols.Length > 0 ? cols[0].Replace("//", "")?.Trim() : "",
                        Value = cols.Length > 1 ? cols[1]?.Trim() : "",
                        ShowCheckBox = true,
                        ShowBtnDel = true,
                        IsChecked = !line.StartsWith("//"),
                    });
                }
            }
            ParamsList.Clear();
            ParamsList.AddRange(currList);
            ParamsList.Add(new ParamsModel()
            {
                ShowWaterMark = true,
            });
            UpdateUrl();
            #endregion
        }


        /// <summary>
        /// 选中所有
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnCheckedAll_ParamsList(bool isChecked)
        {
            if (ParamsList == null || !ParamsList.Any())
            {
                return;
            }
            ParamsListAllChecked = isChecked;
            UpdateUrl(true);
        }


        /// <summary>
        /// 变更Url地址
        /// </summary>
        /// <param name="isAllChecked"></param>
        public void UpdateUrl(bool isAllChecked = false)
        {
            List<string> lst = new List<string>();
            var currList = ParamsList.Where(x => x.ShowCheckBox).ToList();
            foreach (var item in currList)
            {
                if (isAllChecked)
                    item.IsChecked = ParamsListAllChecked;
                //增加Url参数
                if (item.IsChecked)
                {
                    lst.Add($"{item.Key}={item.Value}");
                }
            }
            string baseUrl = string.Empty;
            string paramQuery = string.Join("&", lst);
            if (Url.NotNull())
            {
                bool isUri = Uri.TryCreate(Url, UriKind.Absolute, out var uri);
                if (isUri)
                {
                    baseUrl = uri.GetLeftPart(UriPartial.Path);
                }
                else
                {
                    string[] urlArr = Url.Split(new char[] { '?' }, StringSplitOptions.RemoveEmptyEntries);
                    baseUrl = urlArr[0];
                }

            }

            Url = paramQuery.NotNull() ? $"{baseUrl}?{paramQuery}" : baseUrl;

        }

        /// <summary>
        /// 选中单个单元格
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnChecked_ParamsList(ParamsModel model)
        {
            UpdateUrl();
        }

        /// <summary>
        /// Url参数文本框变更
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnTextChanged_ParamsList(object sender, TextChangedEventArgs e)
        {
            var textBox = (TextBox)sender;
            if (string.IsNullOrWhiteSpace(textBox.Text))
                return;
            var row = textBox.TryGetParentFromVisualTree<DataGridRow>();
            if (row == null)
                return;
            var currModel = row.Item as ParamsModel;
            if (currModel == null)
                return;

            UpdateUrl();
            var index = ParamsList.TakeWhile(m => m.UniqueId != currModel.UniqueId).Count();
            if (index != ParamsList.Count - 1)
            {
                return;
            }

            if (!currModel.ShowCheckBox)
            {
                currModel.ShowCheckBox = true;
                currModel.ShowBtnDel = true;
                currModel.IsChecked = true;
            }
            currModel.ShowWaterMark = false;

            ParamsList.Add(new ParamsModel()
            {
                ShowWaterMark = true,
            });

        }

        /// <summary>
        /// 删除参数行数据
        /// </summary>
        /// <param name="model"></param>
        public void OnRowDelete(ParamsModel model)
        {
            ParamsList.Remove(model);
            //更新Url参数内容
            UpdateUrl();
        }
        #endregion
    }
}